package com.vehiclemanagement.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.vehiclemanagement.entity.Vehicle;
import com.vehiclemanagement.mapper.VehicleMapper;
import com.vehiclemanagement.service.VehicleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 车辆服务实现类
 */
@Service
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements VehicleService {

    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public IPage<Vehicle> pageVehicles(int current, int size, String searchTerm, String vehicleType, Integer status, Boolean includeDeleted) {
        // 创建查询条件
        QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<>();
        
        // 添加搜索条件
        if (searchTerm != null && !searchTerm.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("plate_number", searchTerm)
                .or()
                .like("brand", searchTerm)
                .or()
                .like("vehicle_type", searchTerm));
        }
        
        // 添加车辆类型过滤
        if (vehicleType != null && !vehicleType.isEmpty()) {
            queryWrapper.eq("vehicle_type", vehicleType);
        }
        
        // 添加状态过滤
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        // 是否包含已删除数据
        if (includeDeleted == null || !includeDeleted) {
            queryWrapper.eq("del_flag", 0); // 未删除
        }
        
        // 默认按创建时间排序
        queryWrapper.orderByDesc("create_time");
        
        // 分页查询
        return baseMapper.selectPage(new Page<>(current, size), queryWrapper);
    }
    
    @Override
    public IPage<Vehicle> pageVehicles(int current, int size, String searchTerm, String vehicleType, Integer status, Boolean includeDeleted, String orderBy, String orderType) {
        // 创建查询条件
        QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<>();
        
        // 添加搜索条件
        if (searchTerm != null && !searchTerm.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("plate_number", searchTerm)
                .or()
                .like("brand", searchTerm)
                .or()
                .like("vehicle_type", searchTerm));
        }
        
        // 添加车辆类型过滤
        if (vehicleType != null && !vehicleType.isEmpty()) {
            queryWrapper.eq("vehicle_type", vehicleType);
        }
        
        // 添加状态过滤
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        // 是否包含已删除数据
        if (includeDeleted == null || !includeDeleted) {
            queryWrapper.eq("del_flag", 0); // 未删除
        }
        
        // 添加排序
        if (orderBy != null && !orderBy.isEmpty()) {
            // 将驼峰命名转换为下划线命名，适应数据库字段
            String dbFieldName = camelToUnderline(orderBy);
            
            if ("descending".equals(orderType) || "desc".equals(orderType)) {
                queryWrapper.orderByDesc(dbFieldName);
            } else {
                queryWrapper.orderByAsc(dbFieldName);
            }
        } else {
            // 默认按创建时间排序
            queryWrapper.orderByDesc("create_time");
        }
        
        // 分页查询
        return baseMapper.selectPage(new Page<>(current, size), queryWrapper);
    }
    
    @Override
    public IPage<Vehicle> pageVehiclesWithMultiSort(int current, int size, String searchTerm, String vehicleType, Integer status, Boolean includeDeleted, String orderFieldsJson) {
        // 创建查询条件
        QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<>();
        
        // 添加搜索条件
        if (searchTerm != null && !searchTerm.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                .like("plate_number", searchTerm)
                .or()
                .like("brand", searchTerm)
                .or()
                .like("vehicle_type", searchTerm));
        }
        
        // 添加车辆类型过滤
        if (vehicleType != null && !vehicleType.isEmpty()) {
            queryWrapper.eq("vehicle_type", vehicleType);
        }
        
        // 添加状态过滤
        if (status != null) {
            queryWrapper.eq("status", status);
        }
        
        // 是否包含已删除数据
        if (includeDeleted == null || !includeDeleted) {
            queryWrapper.eq("del_flag", 0); // 未删除
        }
        
        try {
            // 解析多字段排序参数
            System.out.println("开始解码URL参数: " + orderFieldsJson);
            String decodedJson = java.net.URLDecoder.decode(orderFieldsJson, "UTF-8");
            System.out.println("URL解码后: " + decodedJson);
            
            JSONArray sortFields = JSON.parseArray(decodedJson);
            System.out.println("解析后的排序字段数组大小: " + sortFields.size());
            
            // 应用排序字段
            for (int i = 0; i < sortFields.size(); i++) {
                JSONObject sortField = sortFields.getJSONObject(i);
                String field = sortField.getString("field");
                String order = sortField.getString("order");
                
                System.out.println("处理排序字段[" + i + "]: field=" + field + ", order=" + order);
                
                if (field != null && !field.isEmpty()) {
                    // 将驼峰命名转换为下划线命名，适应数据库字段
                    String dbFieldName = camelToUnderline(field);
                    System.out.println("应用排序: " + dbFieldName + " " + order);
                    
                    if ("descending".equals(order) || "desc".equals(order)) {
                        queryWrapper.orderByDesc(dbFieldName);
                    } else {
                        queryWrapper.orderByAsc(dbFieldName);
                    }
                }
            }
            
            // 打印最终的SQL语句
            String finalSql = queryWrapper.getTargetSql();
            System.out.println("最终生成的SQL条件: " + finalSql);
            
        } catch (Exception e) {
            System.err.println("解析排序字段失败: " + e.getMessage());
            e.printStackTrace();
            // 默认排序
            queryWrapper.orderByDesc("create_time");
        }
        
        // 分页查询
        Page<Vehicle> page = new Page<>(current, size);
        IPage<Vehicle> result = baseMapper.selectPage(page, queryWrapper);
        System.out.println("查询完成，总记录数: " + result.getTotal() + ", 当前页记录数: " + result.getRecords().size());
        
        return result;
    }

    /**
     * 驼峰命名转下划线命名
     * 例如：plateNumber -> plate_number
     */
    private String camelToUnderline(String camelCaseName) {
        if (camelCaseName == null || camelCaseName.isEmpty()) {
            return "";
        }
        
        StringBuilder result = new StringBuilder();
        result.append(Character.toLowerCase(camelCaseName.charAt(0)));
        
        for (int i = 1; i < camelCaseName.length(); i++) {
            char ch = camelCaseName.charAt(i);
            if (Character.isUpperCase(ch)) {
                result.append("_");
                result.append(Character.toLowerCase(ch));
            } else {
                result.append(ch);
            }
        }
        
        return result.toString();
    }

    @Override
    public Vehicle getVehicleById(Long id) {
        return vehicleMapper.selectById(id);
    }

    @Override
    public boolean existsActiveVehicleWithPlateNumber(String plateNumber) {
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Vehicle::getPlateNumber, plateNumber)
                   .eq(Vehicle::getDelFlag, 0); // 查询未删除的车辆
        
        return vehicleMapper.selectCount(queryWrapper) > 0;
    }
    
    /**
     * 根据字段名获取排序函数
     */
    private SFunction<Vehicle, ?> getOrderFunction(String orderBy) {
        switch (orderBy) {
            case "id":
                return Vehicle::getId;
            case "plateNumber":
                return Vehicle::getPlateNumber;
            case "vehicleType":
                return Vehicle::getVehicleType;
            case "brand":
                return Vehicle::getBrand;
            case "model":
                return Vehicle::getModel;
            case "status":
                return Vehicle::getStatus;
            case "createTime":
                return Vehicle::getCreateTime;
            default:
                return Vehicle::getCreateTime;
        }
    }
    
    /**
     * 检查车辆是否存在（根据ID）
     */
    @Override
    public boolean exists(Long id) {
        return getById(id) != null;
    }

    @Override
    public boolean addVehicle(Vehicle vehicle) {
        System.out.println("服务层开始添加车辆: " + vehicle);
        
        try {
            // 先检查是否存在未删除的相同车牌号
            if (existsActiveVehicleWithPlateNumber(vehicle.getPlateNumber())) {
                System.out.println("添加车辆失败：车牌号已存在且未删除 - " + vehicle.getPlateNumber());
                return false;
            }
            
            // 设置默认值
            if (vehicle.getCreateTime() == null) {
                vehicle.setCreateTime(LocalDateTime.now());
            }
            if (vehicle.getUpdateTime() == null) {
                vehicle.setUpdateTime(LocalDateTime.now());
            }
            if (vehicle.getDelFlag() == null) {
                vehicle.setDelFlag(0);
            }
            
            // 确保购买日期存在
            if (vehicle.getPurchaseDate() == null) {
                vehicle.setPurchaseDate(LocalDateTime.now());
                System.out.println("购买日期为空，设置为当前时间");
            }
            
            // 确保车辆状态有默认值
            if (vehicle.getStatus() == null) {
                vehicle.setStatus(0);
                System.out.println("车辆状态为空，设置为默认值0(空闲)");
            }
            
            // 执行插入
            int result = vehicleMapper.insert(vehicle);
            System.out.println("插入结果: " + result + ", 生成的ID: " + vehicle.getId());
            
            return result > 0;
        } catch (Exception e) {
            System.err.println("添加车辆发生异常: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean updateVehicle(Vehicle vehicle) {
        // 更新时间
        vehicle.setUpdateTime(LocalDateTime.now());
        
        return vehicleMapper.updateById(vehicle) > 0;
    }

    @Override
    public boolean deleteVehicle(Long id) {
        // 使用物理删除
        System.out.println("执行物理删除车辆，ID: " + id);
        
        try {
            // 先查询出车辆信息，方便记录日志
            Vehicle vehicle = vehicleMapper.selectById(id);
            if (vehicle != null) {
                System.out.println("准备物理删除车牌号为 " + vehicle.getPlateNumber() + " 的车辆");
                
                // 直接物理删除记录
                int result = vehicleMapper.deletePhysically(id);
                System.out.println("物理删除结果: " + result);
                return result > 0;
            } else {
                System.out.println("未找到ID为 " + id + " 的车辆，无法删除");
                return false;
            }
        } catch (Exception e) {
            System.err.println("删除车辆时出错: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public List<String> getVehicleTypes() {
        // 查询所有车辆，然后提取不重复的车辆类型
        LambdaQueryWrapper<Vehicle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(Vehicle::getVehicleType);
        queryWrapper.groupBy(Vehicle::getVehicleType);
        
        List<Vehicle> vehicles = vehicleMapper.selectList(queryWrapper);
        return vehicles.stream()
                .map(Vehicle::getVehicleType)
                .filter(StringUtils::isNotBlank)
                .distinct()
                .collect(Collectors.toList());
    }

    @Override
    public List<Vehicle> getAvailableVehicles() {
        // 获取状态为1(正常使用)的车辆
        return baseMapper.selectList(new QueryWrapper<Vehicle>()
                .eq("status", 1)
                .orderByAsc("id"));
    }
    
    @Override
    public List<Vehicle> getAllVehiclesForExport(String searchTerm, String vehicleType, Integer status) {
        // 构建查询条件
        LambdaQueryWrapper<Vehicle> wrapper = new LambdaQueryWrapper<>();
        
        // 添加搜索条件
        if (StringUtils.isNotBlank(searchTerm)) {
            wrapper.like(Vehicle::getPlateNumber, searchTerm)
                  .or().like(Vehicle::getBrand, searchTerm)
                  .or().like(Vehicle::getModel, searchTerm);
        }
        
        // 添加车辆类型过滤
        if (StringUtils.isNotBlank(vehicleType)) {
            wrapper.eq(Vehicle::getVehicleType, vehicleType);
        }
        
        // 添加状态过滤
        if (status != null) {
            wrapper.eq(Vehicle::getStatus, status);
        }
        
        // 默认只查询未删除的记录
        wrapper.eq(Vehicle::getDelFlag, 0);
        
        // 返回所有符合条件的记录
        return list(wrapper);
    }
    
    @Override
    public boolean batchAddVehicles(List<Vehicle> vehicles) {
        if (vehicles == null || vehicles.isEmpty()) {
            return false;
        }
        
        // 设置创建时间
        LocalDateTime now = LocalDateTime.now();
        for (Vehicle vehicle : vehicles) {
            if (vehicle.getCreateTime() == null) {
                vehicle.setCreateTime(now);
            }
            if (vehicle.getUpdateTime() == null) {
                vehicle.setUpdateTime(now);
            }
            if (vehicle.getDelFlag() == null) {
                vehicle.setDelFlag(0);
            }
        }
        
        // 批量保存
        return saveBatch(vehicles);
    }
} 